package com.ns.sbs.oauth.minio.controller;

import com.ns.core.annotations.ReqLog;
import com.ns.core.utils.sg.ResultOk;
import com.ns.sbs.oauth.minio.entry.MinioItem;
import com.ns.sbs.oauth.minio.service.IMinioFileService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 文件处理
 *
 * @author lw
 * @since 2024/08/29
 */
@RestController
@RequestMapping("/sso")
@RequiredArgsConstructor
@CrossOrigin
public class MinioController {

    private final IMinioFileService minioFileService;

    /**
     * 单文件上传
     *
     * @param file 文件模块
     * @return ResultOk
     */
    @PostMapping("/upload")
    @ReqLog(module = "文件模块", name = "上传", authFlag = false)
    public ResultOk upload(MultipartFile file) {
        MinioItem minioItem = new MinioItem();
        BeanUtils.copyProperties(minioFileService.upload(file), minioItem);
        minioFileService.save(minioItem);
        return ResultOk.getSuccessData(minioItem.getUrl());
    }

    /**
     * 单文件下载
     *
     * @param fileName 文件模块
     * @param delete   下载完后是否删除, 请谨慎传参
     * @return ResultOk
     */
    @GetMapping("/download")
    @ReqLog(module = "文件模块", name = "下载")
    public ResultOk download(@RequestParam(value = "fileName") String fileName,
                             @RequestParam(defaultValue = "false") Boolean delete, HttpServletResponse response) {
        minioFileService.fileDownload(fileName, delete, response);
        return ResultOk.getSuccess();
    }

    /**
     * 查看存储的文件列表
     *
     * @param bucket 桶
     * @return ResultOk
     */
    @GetMapping("/list")
    @ReqLog(module = "文件模块", name = "集合")
    public ResultOk fileList(@RequestParam(value = "bucket") String bucket) {
        return ResultOk.getSuccessData(minioFileService.listObjects(bucket));
    }

    /**
     * 删除文件
     *
     * @param bucket 桶
     * @param list   文件名列表
     * @return ResultOk
     */
    @DeleteMapping("/remove")
    @ReqLog(module = "文件模块", name = "删")
    public ResultOk remove(@RequestParam String bucket, @RequestParam List<String> list) {
        return ResultOk.getSuccessData(minioFileService.removeObjects(bucket, list));
    }

}
